<script setup lang="ts">
import { Search } from '@vicons/carbon';
import { isFunction } from 'lodash-es';
import type { Key, TreeOption } from 'naive-ui/es/tree/src/interface';

import { error } from '@/utils/log';
import type { BasicTreeProps } from '@/components/tree/props';

const props = withDefaults(defineProps<BasicTreeProps>(), {
  keyField: 'id',
  labelField: 'label',
  childrenField: 'children',
  defaultExpandAll: true,
  cascade: false,
  checkable: false,
});

const emits = defineEmits<{
  (e: 'afterFetch', value: Recordable[]): void;
  (e: 'check', value: Key[]): void;
  (e: 'select', value: string | number | undefined): void;
}>();

/**
 * 数据
 */
watchImmediate(() => props.request, async fetch => {
  if (isFunction(fetch)) {
    try {
      const res = await fetch();
      localData.value = res[props.listField];
      emits('afterFetch', localData.value);
    } catch (e) {
      error(e as any);
      localData.value = [];
    }
  }
});
const localData = ref([]);

// 搜索关键字
const pattern = ref('');

/**
 * 高度计算
 */
const styleRef = computed(() => {
  return { height: props.height ? props.height : 'auto' };
});

/**
 * TODO 待完善
 */
function handleCheckedKeys(
  values: Key[],
  _option: Array<TreeOption | null>,
  _meta: {
    node: TreeOption | null;
    action: 'select' | 'unselect';
  },
) {
  emits('check', values);
}

function handleSelectedKeys(
  values: Key[],
  _option: Array<TreeOption | null>,
  _meta: {
    node: TreeOption | null;
    action: 'select' | 'unselect';
  },
) {
  if (values.length === 1) {
    emits('select', values[0]);
  } else {
    emits('select', undefined);
  }
}
</script>

<template>
  <NSpace vertical :size="12">
    <NInput v-model:value="pattern" clearable placeholder="请输入搜索关键字">
      <template #suffix>
        <NIcon :component="Search" />
      </template>
    </NInput>
    <NTree
      :style="styleRef"
      :key-field="props.keyField"
      :label-field="props.labelField"
      :disabled-field="props.disabledField"
      :children-field="props.childrenField"
      :default-expand-all="props.defaultExpandAll"
      :show-irrelevant-nodes="false"
      :pattern="pattern"
      :data="localData"
      :multiple="false"
      block-line
      :cascade="props.cascade"
      :checkable="props.checkable"
      :check-on-click="props.checkable"
      :selectable="!props.checkable"
      cancelable
      @check="handleCheckedKeys"
      @update:selected-keys="handleSelectedKeys"
    />
  </NSpace>
</template>

<style scoped lang="less">

</style>
